<template>
  <div class="activities-container">
    <div class="page-header">
      <h2>活动管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        创建活动
      </el-button>
    </div>

    <el-card>
      <el-table
        v-loading="loading"
        :data="activities"
        style="width: 100%"
      >
        <el-table-column prop="title" label="活动标题" min-width="200" />
        <el-table-column prop="type.name" label="活动类型" width="120" />
        <el-table-column label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="max_people" label="最大人数" width="100">
          <template #default="{ row }">
            {{ row.max_people || '不限' }}
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100">
          <template #default="{ row }">
            <el-tag type="warning">{{ row.points }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)">
              {{ getStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="推荐" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_recommended ? 'success' : 'info'">
              {{ row.is_recommended ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上线状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_online ? 'success' : 'danger'">
              {{ row.is_online ? '上线' : '下线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                @click="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑活动' : '创建活动'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>

        <el-form-item label="活动类型" prop="type_id">
          <el-select
            v-model="form.type_id"
            placeholder="请选择活动类型"
            style="width: 100%"
          >
            <el-option
              v-for="type in types"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="form.end_time"
            type="datetime"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="最大人数" prop="max_people">
          <el-input-number
            v-model="form.max_people"
            :min="0"
            placeholder="0表示不限"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="积分" prop="points">
          <el-input-number
            v-model="form.points"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="活动内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入活动内容"
          />
        </el-form-item>

        <el-form-item label="推荐" prop="is_recommended">
          <el-switch v-model="form.is_recommended" />
        </el-form-item>

        <el-form-item label="上线状态" prop="is_online">
          <el-switch v-model="form.is_online" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '../../utils/request'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const activities = ref([])
const types = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref(null)

const form = reactive({
  id: null,
  title: '',
  type_id: '',
  cover_image: '',
  start_time: '',
  end_time: '',
  max_people: 0,
  points: 0,
  content: '',
  is_recommended: false,
  is_online: true
})

const rules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  type_id: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  cover_image: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  points: [
    { required: true, message: '请输入积分', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入活动内容', trigger: 'blur' }
  ]
}

const fetchActivities = async () => {
  loading.value = true
  try {
    const response = await request.get('/activities', {
      params: {
        page: currentPage.value,
        per_page: pageSize.value
      }
    })
    activities.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

const fetchTypes = async () => {
  try {
    const response = await request.get('/activity-types')
    types.value = response.data
  } catch (error) {
    ElMessage.error('获取活动类型失败')
  }
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusType = (activity) => {
  const now = new Date()
  const startTime = new Date(activity.start_time)
  const endTime = new Date(activity.end_time)
  
  if (now > endTime) return 'info'
  if (now < startTime) return 'warning'
  return 'success'
}

const getStatusText = (activity) => {
  const now = new Date()
  const startTime = new Date(activity.start_time)
  const endTime = new Date(activity.end_time)
  
  if (now > endTime) return '已结束'
  if (now < startTime) return '未开始'
  return '进行中'
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = null
  form.title = ''
  form.type_id = ''
  form.cover_image = ''
  form.start_time = ''
  form.end_time = ''
  form.max_people = 0
  form.points = 0
  form.content = ''
  form.is_recommended = false
  form.is_online = true
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (activity) => {
  isEdit.value = true
  Object.assign(form, activity)
  dialogVisible.value = true
}

const handleDelete = async (activity) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个活动吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/activities/${activity.id}`)
    ElMessage.success('删除成功')
    fetchActivities()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleCoverSuccess = (response) => {
  form.cover_image = response.url
}

const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await request.put(`/activities/${form.id}`, form)
      ElMessage.success('修改成功')
    } else {
      await request.post('/activities', form)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchActivities()
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchActivities()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchActivities()
}

onMounted(() => {
  fetchActivities()
  fetchTypes()
})
</script>

<style scoped>
.activities-container {
  padding: 1rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: var(--dark-color);
}

.pagination-container {
  margin-top: 1.5rem;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 